package com.demo1.controller.admin;

import com.demo1.entity.PageBean;
import com.demo1.entity.Pet;
import com.demo1.entity.R;
import com.demo1.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员-产品Controller控制器
 */
@RestController
@RequestMapping("/admin/pet")
public class AdminPetController {

    @Autowired
    private IPetService petService;

    @Value("${petImagesFilePath}")
    private String petImagesFilePath;

    /**
     * 根据条件分页查询
     * @param pageBean
     * @return
     */
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        System.out.println(pageBean);
        Map<String,Object> map=new HashMap<>();
        map.put("name",pageBean.getQuery().trim());
        map.put("start",pageBean.getStart());
        map.put("pageSize",pageBean.getPageSize());
        List<Pet> list = petService.list(map);
        Long total = petService.getTotal(map);

        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("petList",list);
        resultMap.put("total",total);
        return R.ok(resultMap);
    }

    /**
     * 更新图片
     * @param pet
     * @return
     */
    @PostMapping("/saveImage")
    public R saveImage(@RequestBody Pet pet){
        Pet p = petService.getById(pet.getId());
        petService.saveOrUpdate(p);
        return R.ok();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") Integer id){
        petService.removeById(id);
        return R.ok();
    }
    
    /**
     * 添加或者修改
     * @param pet
     * @return
     */
    @PostMapping("/save")
    public R save(@RequestBody Pet pet){
        if(pet.getId()==null || pet.getId()==-1){ // 添加
            petService.add(pet);
        }else{
            petService.update(pet);
        }
        return R.ok();
    }

    /**
     * 根据条件分页查询
     * @return
     */
    @RequestMapping("/list1")
    public R list(@RequestParam String name,@RequestParam Integer start,@RequestParam Integer pageSize){
        Map<String,Object> map=new HashMap<>();
        map.put("name",name);
        map.put("start",start-1);
        map.put("pageSize",pageSize);
        List<Pet> list = petService.list(map);
        Long total = petService.getTotal(map);

        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("petList",list);
        resultMap.put("total",total);
        return R.ok(resultMap);
    }
}
